package thread.zalan;



import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class Solver {

    CyclicBarrier barrier;
    /**内部类*/
    class Worker implements Runnable {

        private String name;

        public Worker(String name) {
            this.name = name;
        }

        public void run() {
            try {
                int await = barrier.await();  //返回一个到达索引
                System.out.println("" + name + "第" + await + "个到达门口");
            } catch (InterruptedException ex) {
                return;
            } catch (BrokenBarrierException ex) {
                return;
            }
        }
    }

    public void eatKFC(int numbers) throws InterruptedException {

        Runnable barrierAction = new Runnable() {
            public void run() {
                System.out.println("都到齐了，看看谁先到的");
            }
        };
        barrier = new CyclicBarrier(numbers, barrierAction);
        new Thread(new Worker("你二叔")).start();
        new Thread(new Worker("你大舅")).start();
        new Thread(new Worker("你七大爷")).start();
        new Thread(new Worker("你五叔")).start();
    }

    public static void main(String[] args) {
        Solver solver = new Solver();
        try {
            solver.eatKFC(4);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
